package map.abstractor.xaml2uimodel.base;

import java.util.ArrayList;
import java.util.List;

import map.abstractor.xaml2uimodel.visitors.Visitor;
import map.abstractor.xaml2uimodel.visitors.XamlVisitor;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;


/**
 * Abstract Class FlexElement implements : Cloneable Visitable
 * 
 * Represent an Flex Xml Element
 */
public class XamlElement extends XMLElement {

	/**
	 * Fields
	 */
	private String Tag;
	
	private ArrayList<XamlProperty> properties;

	/**
	 * Constructor
	 */
	public XamlElement(Element element) {
		super();
		properties = new ArrayList<XamlProperty>();
		setTag(element.getTagName());
	}
	
	/**
	 * Constructor
	 */
	public XamlElement(Node node) {
		super();
		properties = new ArrayList<XamlProperty>();
		setTag(node.getNodeName().toString());
		NamedNodeMap n=node.getAttributes();
		if(n!=null && n.getLength()>0){
			for(int i=0; i<n.getLength(); i++){
				XamlProperty prop=new XamlProperty();
				prop.tag=n.item(i).getNodeName();
				prop.value=n.item(i).getTextContent();
				properties.add(prop);
			}
			if( node.getNodeValue()!=null && node.getNodeValue().trim().length()>0 )
			{
				XamlProperty prop=new XamlProperty();
				prop.tag="Content";
				prop.value=node.getNodeValue();
				properties.add(prop);
				
			}

		}
	}

	/**
	 * Init Attributes from Xml Element
	 * 
	 * @param e :
	 *            SAX Xml Element
	 */
	public void init(Node e) {
		super.init((Element) e);
		properties = new ArrayList<XamlProperty>();
		NamedNodeMap attrs = e.getAttributes();
		if (attrs != null)
			for (int i = 0; i < attrs.getLength(); ++i)
				properties.add(new XamlProperty(attrs.item(i).getNodeName(),
						attrs.item(i).getTextContent()));
	}

	/**
	 * addProperty
	 * 
	 * @param p :
	 *            the property
	 */
	public void addProperty(XamlProperty p) {
		if (p != null)
			this.properties.add(p);
	}


	/**
	 * getAttribute
	 * 
	 * @param name :
	 *            name of attributes
	 * @return value (String) of the attribute #name
	 */
	public String getProperty(String name) {
		String value = null;
		for (XamlProperty prop : properties)
			if (name.equals(prop.getTag()))
				value = prop.getValue();
		return value;
	}

	
	public List<String> getPropertieName(){
		List<String> prop= new ArrayList<String>();
		for(XamlProperty p : properties)
			prop.add(p.tag);
		return prop;
	}
	public void accept(Visitor visitor, Object container) {
		((XamlVisitor)visitor).visit((Element) this, container);
	}

	public void setTag(String tag) {
		Tag = tag;
	}

	public String getTag() {
		return Tag;
	}
	public XamlProperty getPropery(String name)
	{
		for (XamlProperty p :properties)
			if(p.getTag().compareTo(name)==0)
				return p;
				return null;
	}
	
	public List<XamlProperty> getProperties()
	{
		return properties;
	}
}
